package com.talkyun.utils.revised;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class MD5 {
    private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String md5(String src) {
        try {
            return doMd5(src);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static String md5(byte[] src) {
        try {
            return doMd5(src);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static String md5File(String file) {
        try {
            return toHex(doMd5File(file));
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static String md5FileToBase64(String file) {
        try {
            return toBase64(doMd5File(file));
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    private static byte[] doMd5File(String file) throws IOException, NoSuchAlgorithmException {
        FileInputStream fis = null;
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[32 * 1024];
        try {
            fis = new FileInputStream(file);
            for (int read = fis.read(buffer); read > -1; read = fis.read(buffer)) {
                digest.update(buffer, 0, read);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        return digest.digest();
    }

    private static String doMd5(String src) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(src.getBytes());
        return toHex(digest.digest());
    }

    private static String doMd5(byte[] src) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(src);
        return toHex(digest.digest());
    }

    private static String toHex(byte[] buf) {
        char[] str = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte byte0 = buf[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    private static String toBase64(byte[] buf) {
        return Base64.getEncoder().encodeToString(buf);
        // return new sun.misc.BASE64Encoder().encode(buf);
    }
}